/** Copyright 2020 Zhejiang Lab and Zhejiang University. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================
*/


import { ROOT_URL } from '../../config'
import axios from 'axios'
import { parseTime, addSelectField, setDialogContent, setIsDialogOpen, setIsUpdateDialogOpen } from '../utils'
import { axisBottom } from 'd3'

// initial state
const state = {
    errors: "",
    options: {},
    servers: [],
    algorithms: [
        // {
        //     id: 0,
        //     alg_name: 'sbm',
        //     fields: [
        //         {
        //             field_name: 'alpha',
        //             field_value: '0.5',
        //             field_note: "",
        //         },
        //         {
        //             field_name: 'betatestttttttttttttttttt',
        //             field_value: '0.1',
        //             field_note: "",
        //         },
        //         {
        //             field_name: 'lr',
        //             field_value: '0.1',
        //             field_note: "learning rate testttttttttttttttttttttttttt",
        //         }
        //     ]
        // },
        // {
        //     id: 1,
        //     alg_name: 'kd',
        //     fields: []
        // }
    ],
    metrics:[],
    is_dialog_open: false,
    dialog_content: "",
    is_creating: false,
    is_update_dialog_open: false,
}

// getters
const getters = {
}

// actions
const actions = {
    postServer({ dispatch, commit, state }, server_info) {
        if (server_info.username == "") {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "服务器名不得为空")
        }
        else if (server_info.password == "") {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "密码不得为空")
        }
        else if (server_info.password != server_info.password2) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "两次密码不一致")
        }
        else {
            axios.post(`${ROOT_URL}/api/admin/servers`, {
                server_info,
            })
                .then((response) => {
                    console.log("post ok", response)
                    commit('setIsDialogOpen', true)
                    commit('setDialogContent', '新建成功')
                    commit('setIsCreating', false)
                    dispatch('getServers')
                })
                .catch((errors) => {
                    console.log("post error", errors)
                    commit('setErrors', errors)
                    commit('setIsDialogOpen', true)
                    commit('setDialogContent', '新建失败')
                })
        }
    },
    getServers({ commit, state }) {
        axios.get(`${ROOT_URL}/api/admin/servers`, {
        })
            .then((response) => {
                let servers = response.data.servers;
                for (let s of servers) {
                    s.last_login = parseTime(s.last_login);
                }
                servers = servers.map(addSelectField)
                console.log('getservers')
                commit('setServers', servers)
            })
            .catch((errors) => {
                console.log("error", errors)
                commit('setServers', [])
                commit('setErrors', errors)
            })
    },
    deleteServers({ dispatch, commit, state }) {
        let server_ids = []
        state.servers.forEach(server => { if (server.selected) { server_ids.push(server.id) } });
        console.log('selected', server_ids)
        axios.delete(`${ROOT_URL}/api/admin/servers`, {
            params: {
                server_ids: server_ids
            }
        })
            .then((response) => {
                console.log('delete success')
                commit('setIsDialogOpen', true)
                commit('setDialogContent', '删除成功')
                dispatch('getServers')
            })
            .catch((errors) => {
                console.log('delete failure')
                commit('setErrors', errors)
                commit('setIsDialogOpen', true)
                commit('setDialogContent', '删除失败')
                dispatch('getServers')
            })
    },
    postAlgorithm({ dispatch, commit, state }, algorithm_info) {
        console.log("algorithm info", algorithm_info)
        if (algorithm_info.alg_name == "") {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "算法名称不得为空")
        }
        else {
            let names = new Set()
            for (let f of algorithm_info.fields) {
                if (f.field_name == "") {
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", "字段名称不得为空")
                    return
                }
                if (names.has(f.field_name)) {
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", "字段名称不得重复")
                    return
                }
                names.add(f.field_name)
            }
            axios.post(`${ROOT_URL}/api/task/algorithm_info`, algorithm_info)
                .then((response) => {
                    console.log("post ok", response)
                    commit('setIsDialogOpen', true)
                    commit('setDialogContent', '新建成功')
                    dispatch('getAlgorithms')
                }).catch((errors) => {
                    console.log("post error", errors)
                    commit('setErrors', errors)
                    commit('setIsDialogOpen', true)
                    commit('setDialogContent', '新建失败')
                })
        }
    },
    putAlgorithm({ dispatch, commit, state }, algorithm_info) {
        console.log("algorithm info", algorithm_info)
        if (algorithm_info.alg_name == "") {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "算法名称不得为空")
        }
        else {
            let names = new Set()
            for (let f of algorithm_info.fields) {
                if (f.field_name == "") {
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", "字段名称不得为空")
                    return
                }
                if (names.has(f.field_name)) {
                    commit("setIsDialogOpen", true)
                    commit("setDialogContent", "字段名称不得重复")
                    return
                }
                names.add(f.field_name)
            }
            axios.put(`${ROOT_URL}/api/task/algorithm_info`, algorithm_info)
                .then((response) => {
                    console.log("put ok", response)
                    commit('setIsDialogOpen', true)
                    commit('setDialogContent', '更新成功')
                    dispatch('getAlgorithms')
                }).catch((errors) => {
                    console.log("put error", errors)
                    commit('setErrors', errors)
                    commit('setIsDialogOpen', true)
                    commit('setDialogContent', '更新失败')
                })
        }
    },
    getAlgorithms({ commit, state }) {
        axios.get(`${ROOT_URL}/api/task/algorithm_info`, {
        })
            .then((response) => {
                let algorithms = response.data.algorithms;
                console.log('getalgorithms')
                commit('setAlgorithms', algorithms)
            })
            .catch((errors) => {
                console.log("error", errors)
                commit('setAlgorithms', [])
                commit('setErrors', errors)
            })
    },
    deleteAlgorithms({ dispatch, commit, state }, algorithm_ids) {
        console.log('selected', algorithm_ids)
        axios.delete(`${ROOT_URL}/api/task/algorithm_info`, {
            params: {
                algorithm_ids: algorithm_ids
            }
        })
            .then((response) => {
                console.log('delete success')
                commit('setIsDialogOpen', true)
                commit('setDialogContent', '删除成功')
                dispatch('getAlgorithms')
            })
            .catch((errors) => {
                console.log('delete failure')
                commit('setErrors', errors)
                commit('setIsDialogOpen', true)
                commit('setDialogContent', '删除失败')
                dispatch('getAlgorithms')
            })
    },
    postMetric({ dispatch, commit, state }, {metric_info, file}) {
        console.log("metric info", metric_info)
        console.log("file", file)
        if (metric_info.name == "") {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "度量名称不得为空")
        }
        else if (file== null){
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "请上传度量文件")
        }
        else {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('metric_info', JSON.stringify(metric_info));
            axios.post(`${ROOT_URL}/api/visualization/metrics`, formData)
                .then((response) => {
                    console.log("post ok", response)
                    commit('setIsDialogOpen', true)
                    commit('setDialogContent', '新建成功')
                    dispatch('getMetrics')
                }).catch((errors) => {
                    console.log("post error", errors)
                    commit('setErrors', errors)
                    commit('setIsDialogOpen', true)
                    commit('setDialogContent', '新建失败')
                })
        }
    },
    getMetrics({commit, state}) {
        axios.get(`${ROOT_URL}/api/visualization/metrics`, {
        })
            .then((response) => {
                let metrics = response.data.metrics;
                console.log('getMetrics')
                commit('setMetrics', metrics)
            })
            .catch((errors) => {
                console.log("error", errors)
                commit('setMetrics', [])
                commit('setErrors', errors)
            })

    },
    putMetric({ dispatch, commit, state }, {metric_info,file}) {
        const formData = new FormData();
        formData.append('metric_info', JSON.stringify(metric_info));
        console.log("metric info", metric_info)
        if (file != null){
            formData.append('file', file);
        }
        else {
            formData.append('file', null);
        }
        if (metric_info.name == "") {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "度量名称不得为空")
        }
        else {
            axios.put(`${ROOT_URL}/api/visualization/metrics`, formData)
                .then((response) => {
                    console.log("put ok", response)
                    commit('setIsDialogOpen', true)
                    commit('setDialogContent', '更新成功')
                    dispatch('getMetrics')
                }).catch((errors) => {
                    console.log("put error", errors)
                    commit('setErrors', errors)
                    commit('setIsDialogOpen', true)
                    commit('setDialogContent', '更新失败')
                })
        }
    },
    deleteMetric({ dispatch, commit, state }, metric_id) {
        console.log('selected', metric_id)
        axios.delete(`${ROOT_URL}/api/visualization/metrics`, {
            params: {
                metric_id: metric_id
            }
        })
            .then((response) => {
                console.log('delete success')
                commit('setIsDialogOpen', true)
                commit('setDialogContent', '删除成功')
                dispatch('getMetrics')
            })
            .catch((errors) => {
                console.log('delete failure')
                commit('setErrors', errors)
                commit('setIsDialogOpen', true)
                commit('setDialogContent', '删除失败')
                dispatch('getMetrics')
            })
    }

}

const mutations = {
    setErrors(state, errors) {
        state.errors = errors
    },
    setServers(state, servers) {
        state.servers = servers
    },
    setAlgorithms(state, algorithms) {
        state.algorithms = algorithms
    },
    setMetrics(state, metrics) {
        state.metrics = metrics
    },
    select(state, item) {
        item.selected = !item.selected
    },
    unselectAll(state) {
        state.servers.forEach(server => server.selected = false)
    },
    setDialogContent, setIsDialogOpen,
    setIsUpdateDialogOpen,
    setIsCreating(state, v) {
        state.is_creating = v
    }
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}